<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\Common\Constants\StatusConstants;
use App\CustHub\Constants\BhvTagCustRuleTypeConstants;
use App\CustHub\Constants\BhvTagGrpRuleTypeConstants;
use App\CustHub\Constants\ContactTaskCenterTyperConstants;
use App\CustHub\Constants\DurationUnitConstants;
use App\CustHub\Constants\RoomActiveRoomTypeConstants;
use App\CustHub\Constants\TagModuleConstants;
use App\CustHub\Constants\TagGroupSubConstants;
use App\CustHub\Dto\ContactTcContentDto;
use App\CustHub\Mapper\ChContactMapper;
use App\CustHub\Mapper\ChRoomActiveRoomMapper;
use App\CustHub\Mapper\ChRoomMemberMapper;
use App\CustHub\Mapper\ChSmartTagMapper;
use App\CustHub\Mapper\ChSmartTagRuleConfigMapper;
use App\CustHub\Mapper\ChSmartTagRuleMapper;
use App\CustHub\Model\ChContact;
use App\CustHub\Model\ChCorpTag;
use App\CustHub\Model\ChRobot;
use App\CustHub\Model\ChRoom;
use App\CustHub\Model\ChRoomTag;
use App\CustHub\Model\ChSmartTag;
use App\CustHub\Model\ChSmartTagRule;
use App\CustHub\Model\ChSmartTagRuleConfig;
use Carbon\Carbon;
use FriendsOfHyperf\Lock\Exception\LockTimeoutException;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Annotation\Transaction;
use Mine\Exception\NormalStatusException;
use function FriendsOfHyperf\Lock\lock;
use function Hyperf\Collection\data_get;
use function Hyperf\Support\optional;

class ChSmartTagRuleService extends AbstractService
{
    public $mapper;

    #[Inject]
    protected ChSmartTagMapper $smartTagMapper;

    #[Inject]
    protected ChSmartTagRuleConfigMapper $tagRuleConfigMapper;


    public function __construct(ChSmartTagRuleMapper $mapper)
    {
        $this->mapper = $mapper;
    }


    /**
     * 行为标签组
     * @param array $params
     * @return array
     */
    public function behaviorTagGroups(array $params): array
    {
        $uid = $params['uid'];
        $mainUid = $params['main_uid'];

        $keyword = data_get($params,'keyword','');

        $paginate = Db::table('ch_smart_tag as a')
            ->selectRaw("a.id,a.name,a.module,a.is_preset,a.sub_type,b.enable")
            ->leftJoin('ch_smart_tag_rule_config as b',function ($join) use ($uid){
                $join->on('a.id','=','b.tag_group_id')->where('b.uid',$uid);
            })
            ->where('a.main_uid', $mainUid)
            ->where('a.module',TagModuleConstants::BEHAVIOR)
            ->where('a.parent_id',0)
            ->when(!empty($keyword),function ($query) use ($keyword){
                $query->where('a.name','like',"%{$keyword}%");
            })
            ->orderBy('a.sort','desc')
            ->paginate(
                (int)$params['page_size'] ?? $this->smartTagMapper->model::PAGE_SIZE,
                ['*'],
                'page',
                    (int)$params['page'] ?? 1
            );

        $tagList = ChSmartTag::query()
            ->select(['id','name'])
            ->where('uid', $uid)
            ->where('module',TagModuleConstants::BEHAVIOR)
            ->where('parent_id','<>',0)
            ->get()->toArray();

        $paginate->getCollection()->transform(function ($item) use ($uid,$tagList){
            $item->enable = blank($item->enable) ? 0 : $item->enable;

            //获取规则列表
            $data = ChSmartTagRule::query()
                ->select(['robot_ids','extra'])
                ->where('uid', $uid)
                ->where('tag_group_id',$item->id)
                ->get()->toArray();

            $ruleTagList = [];
            $robotIdList = [];

            foreach ($data as $value){
                $extra = json_decode($value['extra'],true);
                if(!empty($extra['rule'])){
                    $rule = $extra['rule'];
                    array_push($ruleTagList,$rule['add_tag_id'],$rule['remove_tag_id']);
                }
                $robotUserIds = !empty($value['robot_ids']) ? json_decode($value['robot_ids'],true) : [];
                foreach ($robotUserIds as $robotUserId){
                    $robotIdList[] = $robotUserId;
                }
            }

            $ruleTagList = array_unique($ruleTagList);
            $robotIdList = array_unique($robotIdList);
            $fileRuleTagName = \Hyperf\Collection\collect($tagList)->filter(function ($item) use ($ruleTagList){
                return in_array($item['id'],$ruleTagList);
            })->map(function ($item){
                return $item['name'];
            })->implode(',');
            $item->ruleTagName = $fileRuleTagName;
            $item->robotIdList = $robotIdList;
            return $item;
        });

        $data = $this->smartTagMapper->setPaginate($paginate);
        return $data;
    }

    public function tagGroups(array $params)
    {
        $uid = $params['uid'];
        $mainUid = $params['main_uid'];
        $module = $params['module'];
        $keyword = data_get($params,'keyword','');

        $paginate = Db::table('ch_smart_tag as a')
            ->selectRaw("a.id,a.name,a.module,a.is_preset,a.sub_type,b.enable")
            ->leftJoin('ch_smart_tag_rule_config as b',function ($join) use ($uid){
                $join->on('a.id','=','b.tag_group_id')->where('b.uid',$uid);
            })
            ->where('a.main_uid', $mainUid)
            ->where('a.module',$module)
            ->where('a.parent_id',0)
            ->when(!empty($keyword),function ($query) use ($keyword){
                $query->where('a.name','like',"%{$keyword}%");
            })
            ->whereRaw('a.deleted_at is NULL')
            ->orderBy('a.sort','desc')
            ->paginate(
                (int)$params['page_size'] ?? $this->smartTagMapper->model::PAGE_SIZE,
                ['*'],
                'page',
                (int)$params['page'] ?? 1
            );

        $paginate->getCollection()->transform(function ($item) use ($uid,$mainUid){
            $item->enable = blank($item->enable) ? 0 : $item->enable;

            $tagList = ChSmartTag::query()
                ->select(['id','name','is_preset','deleted_at'])
                ->where('uid', $uid)
                ->where('parent_id',$item->id)
//                ->withTrashed()
                ->get()->toArray();

            //获取规则列表
            $data = ChSmartTagRule::query()
                ->select(['robot_ids','extra'])
                ->where('uid', $uid)
                ->where('tag_group_id',$item->id)
                ->first();

            $tagNameList = [];
            $robotIdList = [];
            if(empty($data)){
                //时间进程标签
                $baseData = [
                    'uid' => $uid,
                    'main_uid' => $mainUid,
                    'tag_group_id' => $item->id,
                    'enable' => 0
                ];
                //规则初始化
                $rule = [];
                $ruleData = $baseData;
                $ruleData['module'] = $item->module;
                //初始化规则配置
                $extra = [];
                if($item->module == TagModuleConstants::TIME_PROCESS){
                    //时间进程标签只初始化预设的标签
                    $presetTagList = array_filter($tagList,function ($item){
                       return $item['is_preset'] == 1;
                    });
                    foreach ($presetTagList as $tagItem){
                        $rule[] = [
                            'tag_id' => $tagItem['id'],
                            'next_delay' => [
                                'interval' => 28,
                                'unit' => DurationUnitConstants::DAY
                            ]
                        ];
                        $tagNameList[] = $tagItem['name'];
                    }
                    $extra = [
                        'keep_latest_tag' => 0,
                        'auto_make_tag_to_new_contact' => 0,
                        'rule' => $rule
                    ];
                }

                $ruleData['extra'] = json_encode($extra);

                Db::transaction(function () use ($baseData,$ruleData) {
                    $this->tagRuleConfigMapper->save($baseData);
                    return $this->mapper->save($ruleData);
                });
            }else{
                $extra = json_decode($data['extra'],true);
                $rule = $extra['rule'] ?? [];
                $tagGroupByList = array_column($tagList,'name','id');
                foreach ($rule as $ruleItem){
                    if(isset($tagGroupByList[$ruleItem['tag_id']])){
                        $tagNameList[] = $tagGroupByList[$ruleItem['tag_id']];
                    }
                }
                $robotIdList = !empty($data['robot_ids'])? json_decode($data['robot_ids'],true):[];
            }

            $item->ruleTagName = implode('、',$tagNameList);
            $item->robot_count = count($robotIdList);
            return $item;
        });

        $data = $this->smartTagMapper->setPaginate($paginate);
        return $data;
    }

    /**
     * @param array $params
     * @return bool
     */
    #[Transaction]
    public function enableTagGroup(array $params): bool
    {
        $lock = lock('enable_tag_group_lock'.$params['tag_group_id'],4);
        try {
            $lock->block(2);
            $info = $this->tagRuleConfigMapper->findByTagGroupId($params['uid'],$params['tag_group_id']);
            if(empty($info)){
                $info = new ChSmartTagRuleConfig();
                $info->tag_group_id = $params['tag_group_id'];
                $info->uid = $params['uid'];
                $info->main_uid = $params['main_uid'];
                $info->enable = $params['enable'];
                $result = $info->save();
                $this->tagRuleConfigMapper->clearCache($params['uid'],$params['tag_group_id']);
            }else{
                $result = $this->tagRuleConfigMapper->update($info['id'],[
                    'enable' => $params['enable']
                ]);
            }
            ChSmartTagRule::query()
                ->where('uid',$params['uid'])
                ->where('tag_group_id',$params['tag_group_id'])
                ->update([
                    'enable' => $params['enable']
                ]);

            return $result;
        } catch (LockTimeoutException $e) {
            // 无法获取锁...
            throw new NormalStatusException("请勿重复提交");
        } finally {
            optional($lock)->release();
        }
    }

    public function ruleList(array $params)
    {

        $uid = $params['uid'];
        $paginate = ChSmartTagRule::query()
            ->select(['id','sub_type','enable','robot_ids','extra'])
            ->where('uid',$params['uid'])
            ->where('tag_group_id',$params['tag_group_id'])
            ->orderBy('created_at','desc')
            ->paginate((int)$params['page_size'] ?? $this->smartTagMapper->model::PAGE_SIZE);

        $tagList = ChSmartTag::query()
            ->select(['id','name'])
            ->where('uid', $uid)
            ->where('module',TagModuleConstants::BEHAVIOR)
            ->where('parent_id','<>',0)
            ->get()->toArray();

        $tagList = array_column($tagList,'name','id');

        $paginate->getCollection()->transform(function ($item) use ($tagList){
            $extra = json_decode($item->extra,true);
            $rule = $extra['rule'];
            $item->robot_ids = !empty($item->robot_ids) ? json_decode($item->robot_ids,true) : [];

            if($item->sub_type == TagGroupSubConstants::GROUP){
                //客户行为
                $ruleType = data_get($rule,'type',0);
                $rule['type_text'] = BhvTagGrpRuleTypeConstants::getMessage($ruleType);
                if(isset($rule['add_tag_id'])){
                    $rule['add_tag_name'] = $tagList[$rule['add_tag_id']] ?? '';
                }
                if(isset($rule['remove_tag_id'])){
                    $rule['remove_tag_name'] = $tagList[$rule['remove_tag_id']] ?? '';
                }

                $room = $rule['room'] ?? [];
                $tagCount = 0;
                $roomCount = 0;
                foreach ($room as $value){
                    if($value['target_type'] == 1){
                        $tagCount = $tagCount + count($value['room_tag_ids']);
                    }else{
                        $roomCount = $roomCount + count($value['room_wxids']);
                    }
                }
                $rule['tag_count'] = $tagCount;
                $rule['room_count'] = $roomCount;
                $rule['robot_count'] = count($item['robot_ids']);
            }else{
                //客户行为
                $ruleType = data_get($rule,'type',0);
                $unitType = data_get($rule,'unit',0);
                $rule['type_text'] = BhvTagCustRuleTypeConstants::getMessage($ruleType);
                $rule['unit_text'] = DurationUnitConstants::getMessage($unitType);
                if(isset($rule['add_tag_id'])){
                    $rule['add_tag_name'] = $tagList[$rule['add_tag_id']] ?? '';
                }
                if(isset($rule['remove_tag_id'])){
                    $rule['remove_tag_name'] = $tagList[$rule['remove_tag_id']] ?? '';
                }
                $rule['robot_count'] = count($item['robot_ids']);
            }
            $extra['rule'] = $rule;
            $item->extra = $extra;
            return $item;
        });

        return $this->smartTagMapper->setPaginate($paginate);
    }

    public function getTagList(array $params): array
    {
        $paginate = $this->smartTagMapper->model::query()
            ->select(['id','name'])
            ->where('parent_id',$params['tag_group_id'])
            ->when(!empty($params['keyword']),function ($query) use ($params){
                $query->where('name','like','%'.$params['keyword'].'%');
            })
            ->orderBy('sort')
            ->paginate((int)$params['page_size'] ?? $this->smartTagMapper->model::PAGE_SIZE);
        return $this->smartTagMapper->setPaginate($paginate);
    }

    /**
     * 创建规则
     * @param array $params
     * @return mixed
     */
    public function createRule(array $params): mixed
    {
        $smartTagInfo = ChSmartTag::query()
            ->where('id',$params['tag_group_id'])
            ->first();
        if(empty($smartTagInfo)){
            throw new NormalStatusException('标签组不存在');
        }

        $params['module'] = $smartTagInfo['module'];
        $params['sub_type'] = $smartTagInfo['sub_type'];

        $rule = json_decode($params['rule'],true);
        $extra = [
            'rule' => $rule
        ];
        $params['extra'] = json_encode($extra);

        $ruleId = $this->mapper->save($params);

        if($smartTagInfo->module == TagModuleConstants::BEHAVIOR && $smartTagInfo->sub_type == 0){
            //行为标签-社群行为-处理生效群
            container()->get(ChRoomActiveRoomService::class)->roomSmartTagRuleSave($ruleId,$params['uid'],$params['main_uid'],$rule);
        }

        return $ruleId;
    }

    /**
     * 编辑规则
     * @param array $params
     * @return bool
     */
    #[Transaction]
    public function updateRule(array $params): bool
    {
        $info = ChSmartTagRule::query()
            ->where('id',$params['id'])
            ->where('uid',$params['uid'])
            ->first();
        if(empty($info)){
            throw new NormalStatusException("请选择你要编辑的规则");
        }

        $rule = json_decode($params['rule'],true);
        if($info['module'] == TagModuleConstants::LIFE_CYCLE){
            //生命周期
            //处理企业微信标签
            $corpTagIds = [];
            foreach ($rule as $item){
                if(!empty($item['corp_tag']['ids'])){
                    //企微号的情况
                    $corpTagIds = array_merge($corpTagIds,$item['corp_tag']['ids']);
                }
            }
            $corpTagIds = array_unique($corpTagIds);
            $params['corp_tag_wxids'] = json_encode($corpTagIds);
            ChSmartTagRuleConfig::query()
                ->where('uid',$params['uid'])
                ->where('tag_group_id',$info['tag_group_id'])
                ->update([
                    'enable' => $params['enable']
                ]);
        }


        $extraFields = ['remove_other_tags','keep_latest_tag','auto_make_tag_to_new_contact'];
        foreach ($extraFields as $field){
            if(isset($params[$field]) && filled($params[$field])){
                $extra[$field] = $params[$field];
            }
        }

        $extra['rule'] = $rule;
        $params['extra'] = json_encode($extra);

        $rst = $this->update($params['id'],$params);

        if($info->module == TagModuleConstants::BEHAVIOR && $info->sub_type == 0){
            //行为标签-社群行为-处理生效群
            container()->get(ChRoomActiveRoomService::class)->roomSmartTagRuleSave((int)$params['id'],$params['uid'],$params['main_uid'],$rule);
        }

        return $rst;
    }


    /**
     * 行为标签编辑初始化信息
     * @param array $params
     * @return mixed
     */
    public function getRuleInfo(array $params): mixed
    {
        $info = ChSmartTagRule::query()
            ->select(['id','sub_type','corp_id','corp_tag_wxids','extra','robot_ids'])
            ->where('id',$params['id'])
            ->where('uid',$params['uid'])
            ->first();
        if(empty($info)){
            throw new NormalStatusException('规则不存在');
        }

        $info->robot_ids = json_decode($info->robot_ids,true);
        $extra = json_decode($info->extra,true);
        $robotList = ChRobot::query()
            ->select(['id','nickname','avatar','corp_name','user_id'])
            ->whereIn('id',$info->robot_ids)
            ->get()->toArray();
        if($info->sub_type == 0){
            $robotMap = array_column($robotList,null,'id');
            $room = $extra['rule']['room'];
            foreach ($room as $k=>$roomItem){
                $robotId = $roomItem['robot_id'];
                $room[$k]['id'] = $robotId;
                $room[$k]['nickname'] = $robotMap[$robotId]['nickname'] ?? '';
                $room[$k]['avatar'] = $robotMap[$robotId]['avatar'] ?? '';
                $room[$k]['corp_name'] = $robotMap[$robotId]['corp_name'] ?? '';
                $room[$k]['user_id'] = $robotMap[$robotId]['user_id'] ?? '';
                $roomTagNames = [];
                if($roomItem['target_type'] == 0){
                    $roomWxids = $roomItem['room_wxids'];
                    $roomList = ChRoom::query()
                        ->select(['id','room_wxid','room_name','room_avatar_url'])
                        ->whereHas('robots',function ($query) use ($robotId){
                            $query->where('robot_id',$robotId);
                        })->whereIn('room_wxid',$roomWxids)
                        ->get()->toArray();
                }else{
                    $roomList = [];
                    if(!empty($roomItem['room_tag_ids'])){
                        $roomTagNames = ChRoomTag::query()
                            ->whereIn('id',$roomItem['room_tag_ids'])
                            ->pluck('name')
                            ->toArray();
                    }
                }
                $room[$k]['room_list'] = $roomList;
                $room[$k]['room_tag_names'] = $roomTagNames;
            }
            $extra['rule']['room'] = $room;
        }
        $info->extra = $extra;
        $info->robot_list = $robotList;
        return $info;
    }

    /**
     * 删除规则
     * @param array $params
     * @return bool|int|mixed|null
     * @throws \Exception
     */
    #[Transaction]
    public function delRule(array $params): mixed
    {
        $info = ChSmartTagRule::query()
            ->where('id',$params['id'])
            ->where('main_uid',$params['main_uid'])
            ->first();

        if(empty($info)){
            throw new NormalStatusException('规则不存在');
        }

        if($info->module == TagModuleConstants::BEHAVIOR && $info->sub_type == 0){
            //行为标签-社群行为-删除生效群
            container()->get(ChRoomActiveRoomService::class)->deleteActiveRoom([$params['id']],json_decode($info->robot_ids,true),RoomActiveRoomTypeConstants::SMART_TAG_GROUP_BEHAVIOR);
        }
        return $info->delete();
    }

    public function newRuleItem(array $params)
    {
        $uid = $params['uid'];
        $mainUid = $params['main_uid'];
        $tagGroupId = $params['tag_group_id'];
        $corpId = data_get($params,'corp_id',0);

        //不存在规则 这初始化一条默认的规则
        $smartTagInfo = ChSmartTag::query()
            ->select(['id','module'])
            ->where('id',$tagGroupId)
            ->first();
        if(empty($smartTagInfo)){
            throw new NormalStatusException('分组不存在');
        }
        $module = $smartTagInfo->module;

        $info = ChSmartTagRule::query()
            ->select(['id','enable','corp_id','corp_tag_wxids','extra','robot_ids'])
            ->where('uid',$uid)
            ->where('tag_group_id',$params['tag_group_id'])
            ->first();

        $tagList = ChSmartTag::query()
            ->select(['id','name','module'])
            ->where('parent_id',$tagGroupId)
            ->orderBy('sort')
            ->get()->toArray();
        if(!empty($info)){
            $extra = json_decode($info['extra'],true);
        }else{
            $extra = [];
        }
        if(empty($extra) || empty($extra['rule'])){
            if(!empty($info)){
                $ruleId = $info['id'];
            }else{
                $ruleId = null;
            }
            $result = $this->emptyRuleCase($uid,$mainUid,$tagGroupId,$corpId,$module,$tagList,$ruleId);
        }else{
            $result = $this->notEmptyRuleCase($info,$module,$tagList);
        }
        return $result;
    }

    /**
     * 规则为空的情况
     * @param $uid
     * @param $mainUid
     * @param $tagGroupId
     * @param $corpId
     * @param $module
     * @param $tagList
     * @return array
     */
    private function emptyRuleCase($uid,$mainUid,$tagGroupId,$corpId,$module,$tagList,$ruleId): array
    {
        $baseData = [
            'uid' => $uid,
            'main_uid' => $mainUid,
            'tag_group_id' => $tagGroupId,
            'enable' => 0
        ];
        //规则初始化
        $rule = [];
        $ruleData = $baseData;
        $ruleData['corp_id'] = $corpId;
        $ruleData['module'] = $module;

        if($module == TagModuleConstants::CUSTOMER_VALUE){
            $extra['remove_other_tags'] = 0;
        }elseif($module == TagModuleConstants::TIME_PROCESS){
            $extra['keep_latest_tag'] = 0;
            $extra['auto_make_tag_to_new_contact'] = 0;
        }

        $extra['rule'] = $rule;

        $ruleData['extra'] = json_encode($extra);

        if(is_null($ruleId)){
            $ruleId = Db::transaction(function () use ($baseData,$ruleData) {
                $this->tagRuleConfigMapper->save($baseData);
                return $this->mapper->save($ruleData);
            });
        }

        $result = [
            'id' => $ruleId,
            'corp_id' => $corpId,
            'corp_tag_wxids' => [],
            'extra' => $extra,
            'robot_ids' => [],
            'robot_list' => []
        ];
        $newRuleList = [];
        foreach ($tagList as $item){
            if($item['module'] == TagModuleConstants::LIFE_CYCLE){
                $newRuleList[] = [
                    'tag_id' => $item['id'],
                    'name' => $item['name'],
                    'cond_operator' => 'and',
                    'corp_tag' => '',
                    'smart_tag' => ''
                ];
            }elseif($item['module'] == TagModuleConstants::CUSTOMER_VALUE){
                $newRuleList[] = [
                    'tag_id' => $item['id'],
                    'name' => $item['name'],
                    'cond_operator' => 'and',
                    'cond_items' => [
                    ]
                ];
            }
        }
        $result['extra']['rule'] = $newRuleList;
        return $result;
    }

    /**
     * 规则不为空的情况
     * @param $info
     * @param $module
     * @param $tagList
     * @return mixed
     */
    private function notEmptyRuleCase($info,$module,$tagList)
    {
        $info->robot_ids = !empty($info->robot_ids) ? json_decode($info->robot_ids,true) : [];
        $info->corp_tag_wxids = !empty($info->corp_tag_wxids) ? json_decode($info->corp_tag_wxids,true) : [];
        if(!empty($info->extra)){
            $info->extra = json_decode($info->extra,true);
        }else{
            if($module == TagModuleConstants::CUSTOMER_VALUE){
                $extra['remove_other_tags'] = 0;
            }elseif($module == TagModuleConstants::TIME_PROCESS){
                $extra['keep_latest_tag'] = 0;
                $extra['auto_make_tag_to_new_contact'] = 0;
            }else{
                $extra = [];
            }
            $info->extra = $extra;
        }

        $result = $info->toArray();
        $robotList = [];
        if(!empty($result['robot_ids'])){
            $robotList = ChRobot::query()
                ->select(['id','nickname','avatar','corp_name','user_id'])
                ->whereIn('id',$info->robot_ids)
                ->get()->toArray();
        }
        $result['robot_list'] = $robotList;

        $tagMap = array_column($tagList,'name','id');
        $ruleList = $result['extra']['rule'] ?? [];

        foreach ($ruleList as $ruleKey => $ruleItem){
            $ruleList[$ruleKey]['name'] = $tagMap[$ruleItem['tag_id']] ?? '';
            if($module == TagModuleConstants::LIFE_CYCLE){
                if(!empty( $ruleItem['corp_tag'])){
                    $ruleList[$ruleKey]['corp_tag']['match_type_text'] =  $ruleItem['corp_tag']['match_type'] == 0 ? '含任意标签' : '所有标签';

                    if(!empty($ruleItem['corp_tag']['ids'])){
                        $corpTagNameList = ChCorpTag::query() ->whereIn('id',$ruleItem['corp_tag']['ids'])
                            ->pluck('name')
                            ->toArray();
                        $corpTagIdsName = implode('、',$corpTagNameList);
                    }else{
                        $corpTagIdsName = '';
                    }
                    $ruleList[$ruleKey]['corp_tag']['ids_text'] = $corpTagIdsName;
                }

                if(!empty($ruleItem['smart_tag'])){
                    $ruleList[$ruleKey]['smart_tag']['match_type_text'] =  $ruleItem['smart_tag']['match_type'] == 0 ? '含任意标签' : '所有标签';
                    if(!empty($ruleItem['smart_tag']['ids'])){
                        $smartTagNameList = ChSmartTag::query() ->whereIn('id',$ruleItem['smart_tag']['ids'])
                            ->pluck('name')
                            ->toArray();
                        $smartTagIdsName = implode('、',$smartTagNameList);
                    }else{
                        $smartTagIdsName = '';
                    }
                    $ruleList[$ruleKey]['smart_tag']['ids_text'] = $smartTagIdsName;
                }

            }elseif ($module == TagModuleConstants::CUSTOMER_VALUE){
                $condItems = $ruleItem['cond_items'];
                $ruleList[$ruleKey]['cond_items'] = $this->transformCondItems($condItems);
            }
        }
        $result['extra']['rule'] = $ruleList;
        return $result;
    }

    /**
     * 转换配置
     * @param array $data
     * @return array
     */
    public function transformConfig(array $data): array
    {
        $condItems = !empty($data['cond_items']) ? json_decode($data['cond_items'],true) : [];
        return $this->transformCondItems($condItems);
    }


    private function transformCondItems(array $condItems): array
    {
        foreach ($condItems as $cik => $condItem){
            $unit = '次';
            if($condItem['type'] == 0){
                $text = "消费间隔：";
            }elseif ($condItem['type'] == 1){
                if($condItem['date_filter_type'] == 0){
                    $text = "消费频次：";
                }elseif($condItem['date_filter_type'] == 1){
                    $text = "近{$condItem['date_filter_value']}天，消费频次：";
                }else{
                    $text = "{$condItem['date_filter_value'][0]}~{$condItem['date_filter_value'][1]}，消费频次：";
                }
            }else{
                $unit = '元';
                if($condItem['date_filter_type'] == 0){
                    $text = "消费金额：";
                }elseif($condItem['date_filter_type'] == 1){
                    $text = "近{$condItem['date_filter_value']}天，消费金额：";
                }else{
                    $text = "{$condItem['date_filter_value'][0]}~{$condItem['date_filter_value'][1]}，消费金额：";
                }
            }


            $cons_rule = $this->describeRange($condItem['cons_rule'],$unit);
            $condItems[$cik]['text'] = $text .$cons_rule;
        }
        return $condItems;
    }

    private function describeRange(string $range,string $unit): string
    {
        // 去除空格
        $range = trim($range);

        // 正则表达式匹配，提取边界符号和数字
        preg_match('/^([\[\(])\s*(-?\d+\.?\d*)\s*,\s*(-?\d+\.?\d*)\s*([\]\)])$/', $range, $matches);

        if (count($matches) !== 5) {
            throw new NormalStatusException("表达式不符合规范");
        }

        // 提取结果
        $leftBound = $matches[1];  // 左边界符号
        $minValue = $matches[2];   // 最小值
        $maxValue = $matches[3];   // 最大值
        $rightBound = $matches[4]; // 右边界符号

        // 构建描述字符串
        $description = '';

        if ($leftBound === '[') {
            $description .= "大于等于{$minValue}{$unit}";
        } else {
            $description .= "大于{$minValue}{$unit}";
        }

        $description .= "，";

        if ($rightBound === ']') {
            $description .= "小于等于{$maxValue}{$unit}";
        } else {
            $description .= "小于{$maxValue}{$unit}";
        }

        return $description;
    }

    /**
     * 定时处理私聊活跃度规则
     * @return void
     */
    public function timedHandler()
    {
        $list = ChSmartTagRule::query()
            ->where('module',TagModuleConstants::BEHAVIOR)
            ->where('sub_type',1)
            ->where('enable',StatusConstants::ENABLE)
            ->get();

        foreach ($list as $item){
            $robotIds = json_decode($item->robot_ids,true);
            $extra = json_decode($item->extra,true)['rule'];
            $duration = $extra['duration'];
            $unit = $extra['unit'];
            //0=加好友后 1=连续
            $type = $extra['type'];

            if($unit == 0){
                $date = Carbon::now()->subDays($duration)->toDateString();
            }else{
                $date = Carbon::now()->subHours($duration)->toDateString();
            }
            $addTagId = $extra['add_tag_id'];
            $removeTagId = $extra['remove_tag_id'];
            foreach ($robotIds as $robotId){
                // 查询未添加标签且最后发送消息时间小于等于指定日期的客户
                $contacts = ChContact::query()
                    ->where('robot_id',$robotId)
                    ->whereDoesntHave('smartTags',function ($query) use ($addTagId){
                        $query->where('smart_tag_id',$addTagId);
                    })
                    ->where(function ($query) use ($type,$date){
                        if($type == 0){
                            $query->where('add_customer_time', '<', $date)
                                ->whereNull('last_send_msg_time');
                        }else{
                            $query->whereNull('last_send_msg_time')
                                ->orWhere('last_send_msg_time', '<', $date);
                        }
                    })
                    ->get();

                foreach ($contacts as $contact){
                    $content = new ContactTcContentDto();
                    $content->setContactIds([$contact->id]);
                    $content->setTagIds([$addTagId]);
                    $content->setRemoveTagIds([$removeTagId]);
                    container()->get(ChContactTaskCenterService::class)->addTask($contact->uid,$contact->main_uid,ContactTaskCenterTyperConstants::MOVE_SMART_TAG,$content);
                }
            }
        }
    }

    /**
     * 定时处理群聊活跃度规则
     * @return void
     */
    public function roomRuleHandler(int $robotId,string $userId,string $roomWxid = ''): void
    {
        $contactInfo = container()->get(ChContactMapper::class)->findByRobotIdAndUserId($robotId,$userId);
        if(empty($contactInfo)){
            return;
        }

        $list = container()->get(ChRoomActiveRoomMapper::class)->findByRobotIdAndRoomWxid($robotId,$roomWxid,RoomActiveRoomTypeConstants::SMART_TAG_GROUP_BEHAVIOR);
        $roomMemberMapper = container()->get(ChRoomMemberMapper::class);
        foreach ($list as $item){
            $schemeInfo = ChSmartTagRule::query()
                ->where('id',$item->scheme_id)
                ->first();

            if(empty($schemeInfo)){
                continue;
            }

            empty($roomWxid) && $roomWxid = $item['room_wxid'];

            $rule = json_decode($schemeInfo->extra,true)['rule'];
            $addTagId = $rule['add_tag_id'];
            $removeTagId = $rule['remove_tag_id'];
            $type = $rule['type'];
            if($type == 0){
                //已加入群聊
                $flag = $roomMemberMapper->checkRoomMemberExist($roomWxid,$userId,0);
            }elseif($type == 1){
                //未加入群聊
                $flag = !$roomMemberMapper->checkRoomMemberExist($roomWxid,$userId);
            }else{
                //退出群聊
                $flag = $roomMemberMapper->checkRoomMemberExist($roomWxid,$userId,1);
            }

            if($flag){
                //判断当前客户是否存在当前标签，存在的情况不做处理
                $tagIdExists = $contactInfo->smartTags()->where('smart_tag_id',$addTagId)->exists();
                if(!$tagIdExists){
                    $content = new ContactTcContentDto();
                    $content->setContactIds([$contactInfo->id]);
                    $content->setTagIds([$addTagId]);
                    $content->setRemoveTagIds([$removeTagId]);
                    container()->get(ChContactTaskCenterService::class)->addTask($contactInfo->uid,$contactInfo->main_uid,ContactTaskCenterTyperConstants::MOVE_SMART_TAG,$content);
                }
            }
        }
    }
}